#ifndef __TCP_SERVER_H__
#define __TCP_SERVER_H__

#include <memory>
#include <functional>
#include <sstream>
#include "noncopyable.h"
#include "address.h"
#include "iomanager.h"
#include "socket.h"

class TcpServer : public std::enable_shared_from_this<TcpServer>, public Noncopyable
{
public:
    typedef std::shared_ptr<TcpServer> ptr;

    TcpServer(IOManager *io_worker = IOManager::GetThis(), IOManager *accept_worker = IOManager::GetThis());
    virtual ~TcpServer();

    virtual bool bind(Address::ptr addr);
    virtual bool bind(const std::vector<Address::ptr> &addrs, std::vector<Address::ptr> &fails);

    virtual bool start();
    virtual void stop();

    uint64_t getRecvTimeout() const { return m_recvTimeout; }
    std::string getName() const { return m_name; }

    void setRecvTimeout(uint64_t timeout) { m_recvTimeout = timeout; }
    virtual void setName(const std::string &name) { m_name = name; }

    bool isStop() const { return m_isStop; }
    virtual std::string toString(const std::string &prefix = "");

protected:
    // 处理新连接的socket类
    virtual void handleClient(Socket::ptr client);

    // 开始接受连接
    virtual void startAccept(Socket::ptr sock);

protected:
    // 监听socket数组
    std::vector<Socket::ptr> m_socks;
    // 新连接的socket调度器
    IOManager *m_ioWorker;
    // 服务器socket接收连接的调度器
    IOManager *m_acceptWorker;
    // 接收超时时间(毫秒)
    uint64_t m_recvTimeout;
    // 服务器名称
    std::string m_name;
    // 服务器类型
    std::string m_type;
    // 服务是否停止
    bool m_isStop;
};

#endif